// ==UserScript==
// @name         微信公众平台搜索下载器
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  使用token和cookie搜索公众号并下载结果
// @author       George Cai
// @match        https://mp.weixin.qq.com/*
// @grant        GM.xmlHttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // 创建一个按钮容器
    function createButtonContainer() {
        const container = document.createElement('div');
        container.id = 'wechat-search-buttons';
        container.style.position = 'fixed';
        container.style.top = '60px';
        container.style.right = '10px';
        container.style.zIndex = '9999';
        container.style.display = 'flex';
        container.style.flexDirection = 'column';
        container.style.gap = '10px';
        document.body.appendChild(container);
        return container;
    }

    // 创建搜索按钮
    function createSearchButton() {
        const button = document.createElement('button');
        button.innerHTML = '搜索公众号';
        button.style.padding = '10px';
        button.style.backgroundColor = '#07C160';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.borderRadius = '4px';
        button.style.cursor = 'pointer';
        
        button.addEventListener('click', promptAndSearch);
        
        const container = document.getElementById('wechat-search-buttons') || createButtonContainer();
        container.appendChild(button);
    }

    // 创建结果按钮
    function createResultButton(account) {
        const buttonContainer = document.createElement('div');
        buttonContainer.style.display = 'flex';
        buttonContainer.style.flexDirection = 'column';
        buttonContainer.style.gap = '5px';
        buttonContainer.style.marginTop = '5px';
        buttonContainer.style.width = '200px';

        // 主按钮（公众号名称）
        const mainButton = document.createElement('button');
        mainButton.innerHTML = account.nickname;
        mainButton.style.padding = '10px';
        mainButton.style.backgroundColor = '#ffffff';
        mainButton.style.color = '#07C160';
        mainButton.style.border = '1px solid #07C160';
        mainButton.style.borderRadius = '4px';
        mainButton.style.cursor = 'pointer';
        mainButton.style.textAlign = 'left';
        mainButton.style.overflow = 'hidden';
        mainButton.style.textOverflow = 'ellipsis';
        mainButton.style.whiteSpace = 'nowrap';
        mainButton.style.width = '100%';

        // 点击主按钮时显示选项按钮
        mainButton.addEventListener('click', () => {
            // 清除其他所有公众号按钮
            const container = document.getElementById('wechat-search-buttons');
            const buttons = Array.from(container.children);
            buttons.forEach(btn => {
                if (btn !== buttonContainer && btn.tagName !== 'BUTTON') {
                    container.removeChild(btn);
                }
            });

            // 如果选项按钮还没有创建，则创建它们
            if (buttonContainer.children.length === 1) {
                // 创建选项按钮的函数
                function createOptionButton(text, onClick) {
                    const button = document.createElement('button');
                    button.innerHTML = text;
                    button.style.padding = '8px';
                    button.style.backgroundColor = '#f0f0f0';
                    button.style.color = '#333';
                    button.style.border = '1px solid #ddd';
                    button.style.borderRadius = '4px';
                    button.style.cursor = 'pointer';
                    button.style.fontSize = '12px';
                    button.style.width = '100%';
                    button.addEventListener('click', onClick);
                    return button;
                }

                // 创建三个选项按钮
                const weekButton = createOptionButton('最近1周', () => {
                    getArticleList(account.fakeid, account.nickname, {
                        count: 20,
                        filterWeek: true
                    });
                });

                const recentButton = createOptionButton('最近10篇', () => {
                    getArticleList(account.fakeid, account.nickname, {
                        count: 10
                    });
                });

                const searchButton = createOptionButton('关键词搜索', () => {
                    const keyword = prompt('请输入搜索关键词：');
                    if (keyword) {
                        getArticleList(account.fakeid, account.nickname, {
                            count: 20,
                            search_field: 7,
                            query: keyword
                        });
                    }
                });

                // 添加选项按钮
                buttonContainer.appendChild(weekButton);
                buttonContainer.appendChild(recentButton);
                buttonContainer.appendChild(searchButton);
            }
        });

        // 初始只添加主按钮
        buttonContainer.appendChild(mainButton);
        return buttonContainer;
    }

    // 添加JSON解析函数
    function parseNestedJson(data) {
        if (typeof data === 'string') {
            try {
                return parseNestedJson(JSON.parse(data));
            } catch (e) {
                return data;
            }
        } else if (Array.isArray(data)) {
            return data.map(item => parseNestedJson(item));
        } else if (data && typeof data === 'object') {
            const result = {};
            for (const key in data) {
                result[key] = parseNestedJson(data[key]);
            }
            return result;
        }
        return data;
    }

    // 获取文章列表
    function getArticleList(fakeid, nickname, options = {}) {
        const savedData = JSON.parse(localStorage.getItem('wechat_auth_data') || '{}');
        const token = savedData.token;
        const cookies = savedData.raw_set_cookies;

        if (!token || !cookies) {
            alert('认证信息已失效，请重新获取token和cookies！');
            return;
        }

        // 构建文章列表URL
        const urlParams = new URLSearchParams({
            sub: 'list',
            search_field: options.search_field || 'null',
            begin: '0',
            count: options.count || '5',
            query: options.query || '',
            fakeid: fakeid,
            type: '101_1',
            free_publish_type: '1',
            sub_action: 'list_ex',
            token: token,
            lang: 'zh_CN',
            f: 'json',
            ajax: '1'
        });

        const listUrl = `https://mp.weixin.qq.com/cgi-bin/appmsgpublish?${urlParams.toString()}`;

        GM.xmlHttpRequest({
            method: 'GET',
            url: listUrl,
            headers: {
                'Cookie': cookies,
                'Accept': 'application/json, text/plain, */*',
                'Cache-Control': 'no-cache'
            },
            onload: function(response) {
                try {
                    const rawData = JSON.parse(response.responseText);
                    const data = parseNestedJson(rawData);
                    
                    if (data.base_resp && data.base_resp.ret === 200003) {
                        alert('获取文章列表失败：session无效，请重新获取cookie！');
                        return;
                    }

                    const articles = [];
                    if (data.publish_page && data.publish_page.publish_list) {
                        data.publish_page.publish_list.forEach(item => {
                            if (item.publish_info && item.publish_info.appmsgex) {
                                item.publish_info.appmsgex.forEach(article => {
                                    const date = new Date(article.create_time * 1000);
                                    
                                    // 如果需要过滤一周内的文章
                                    if (options.filterWeek) {
                                        const oneWeekAgo = new Date();
                                        oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
                                        if (date < oneWeekAgo) {
                                            return;
                                        }
                                    }

                                    const formattedDate = date.toLocaleString('zh-CN', {
                                        year: 'numeric',
                                        month: '2-digit',
                                        day: '2-digit',
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        hour12: false
                                    }).replace(/\//g, '-');

                                    articles.push({
                                        nickname: nickname,
                                        title: article.title,
                                        link: article.link,
                                        create_time: formattedDate,
                                        author_name: article.author_name || '',
                                        cover: article.cover,
                                    });
                                });
                            }
                        });
                    }

                    // 如果是最近10篇，限制文章数量
                    let finalArticles = articles;
                    if (options.count === 10) {
                        finalArticles = articles.slice(0, 10);
                    }

                    // 生成文件名
                    let fileName = `wechat_articles_${nickname}`;
                    if (options.filterWeek) {
                        fileName += '_last_week';
                    } else if (options.count === 10) {
                        fileName += '_last_10';
                    } else if (options.query) {
                        fileName += `_search_${options.query}`;
                    }
                    fileName += `_${new Date().getTime()}.csv`;

                    // 生成并下载CSV
                    const headers = ['nickname', 'title', 'link', 'create_time', 'author_name', 'cover'];
                    const csvContent = [
                        headers.join(','),
                        ...finalArticles.map(article => 
                            headers.map(header => 
                                JSON.stringify(article[header] || '')
                            ).join(',')
                        )
                    ].join('\n');

                    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);

                } catch (error) {
                    console.error('解析响应失败:', error);
                    alert('解析响应失败，请查看控制台了解详情');
                }
            },
            onerror: function(error) {
                console.error('请求失败:', error);
                alert('请求失败，请查看控制台了解详情');
            }
        });
    }

    // 清除现有的结果按钮
    function clearResultButtons() {
        const container = document.getElementById('wechat-search-buttons');
        const buttons = container.getElementsByTagName('button');
        // 保留第一个搜索按钮，删除其他按钮
        while (buttons.length > 1) {
            container.removeChild(buttons[1]);
        }
    }

    // 显示搜索结果
    function displayResults(list) {
        const container = document.getElementById('wechat-search-buttons');
        clearResultButtons();
        
        list.forEach(account => {
            const button = createResultButton(account);
            container.appendChild(button);
        });
    }

    // 提示输入关键词并搜索
    function promptAndSearch() {
        const keyword = prompt('请输入要搜索的公众号关键词：');
        if (!keyword) return;

        // 从localStorage获取认证信息
        const savedData = JSON.parse(localStorage.getItem('wechat_auth_data') || '{}');
        const token = savedData.token;
        const cookies = savedData.raw_set_cookies;

        if (!token || !cookies) {
            alert('请先使用Cookie获取器获取token和cookies！');
            return;
        }

        // 构建搜索URL
        const searchUrl = `https://mp.weixin.qq.com/cgi-bin/searchbiz?action=search_biz&begin=0&count=5&query=${encodeURIComponent(keyword)}&token=${token}&lang=zh_CN&f=json&ajax=1`;

        // 发送搜索请求
        GM.xmlHttpRequest({
            method: 'GET',
            url: searchUrl,
            headers: {
                'Cookie': cookies,
                'Accept': 'application/json, text/plain, */*',
                'Cache-Control': 'no-cache'
            },
            onload: function(response) {
                try {
                    const data = JSON.parse(response.responseText);
                    
                    if (data.base_resp && data.base_resp.ret === 200003) {
                        alert('搜索失败：session无效，请重新获取cookie！');
                        return;
                    }

                    if (data.list && data.list.length > 0) {
                        displayResults(data.list);
                    } else {
                        alert('未找到相关公众号');
                    }
                } catch (error) {
                    console.error('解析响应失败:', error);
                    alert('解析响应失败，请查看控制台了解详情');
                }
            },
            onerror: function(error) {
                console.error('请求失败:', error);
                alert('请求失败，请查看控制台了解详情');
            }
        });
    }

    // 等待页面加载完成后创建按钮
    window.addEventListener('load', createSearchButton);
})(); 